import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import ProductionPlan from '../views/ProductionPlan.vue'
import InventoryManagement from '../views/InventoryManagement.vue'
import QualityInspection from '../views/QualityInspection.vue'
import Equipment_Management from '../views/Equipment_Management.vue'
import ReportAnalysis from '../views/ReportAnalysis.vue'
import ExceptionHandling from '../views/ExceptionHandling.vue'

const routes = [
  // 仪表盘页面
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  // 登录页
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  // 生产计划页
  {
    path: '/production-plan',
    name: 'ProductionPlan',
    component: ProductionPlan,
    meta: { requiresAuth: true } // 如果需要认证，就加上meta
  },
  // 库存管理页
  {
    path: '/inventory',
    name: 'Inventory',
    component: InventoryManagement,
    meta: { requiresAuth: true }
  },
  // 质检管理页
  {
    path: '/quality-inspection',
    name: 'QualityInspection',
    component: QualityInspection,
    meta: { requiresAuth: true }
  },
  // 设备管理页
  {
    path: '/equipment',
    name: 'Equipment',
    component: Equipment_Management,
    meta: { requiresAuth: true }
  },
  // 报表分析页
  {
    path: '/reports',
    name: 'Reports',
    component: ReportAnalysis,
    meta: { requiresAuth: true }
  },
  // 异常处理页
  {
    path: '/exceptions',
    name: 'Exceptions',
    component: ExceptionHandling,
    meta: { requiresAuth: true }
  }

]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫，处理登录验证和页面跳转
router.beforeEach((to, from, next) => {
  // 检查用户是否已登录
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'

  // 如果用户访问的是需要认证的页面，但未登录
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 重定向到登录页
    next({ name: 'Login' })
  }
  // 如果用户已登录，但访问的是登录页
  else if (isLoggedIn && to.name === 'Login') {
    // 已登录用户访问登录页，重定向到首页
    next({ name: 'Home' })
  }
  // 其他情况正常放行
  else {
    next()
  }
})

export default router
